import React, { memo, useEffect, useRef } from "react";
import { useDispatch, useSelector, shallowEqual } from "react-redux";
import classNames from "classnames";

import {
  getDjRadioCatelistAction,
  changeCurrentIdAction,
} from "../../store/actionCreators";
import { PAGE_SIZE } from "@/common/constants";

import { Carousel } from "antd";
import { CategoryWrapper, CategoryContent, CategoryItemImage } from "./style";
export default memo(function HYRadioCategory() {
  const dispatch = useDispatch();
  const carouselRef = useRef();

  useEffect(() => {
    dispatch(getDjRadioCatelistAction());
  }, [dispatch]);

  const { categories, currentId } = useSelector(
    (state) => ({
      categories: state.getIn(["djRadio", "categories"]),
      currentId: state.getIn(["djRadio", "currentId"]),
    }),
    shallowEqual
  );

  const page = Math.ceil(categories.length / PAGE_SIZE) || 1;

  const getSize = (index) => {
    return index * PAGE_SIZE > categories.length
      ? index * PAGE_SIZE
      : categories.length;
  };
  return (
    <CategoryWrapper>
      <div
        className="arrow arrow-left"
        onClick={(e) => carouselRef.current.prev()}
      ></div>
      <CategoryContent>
        <Carousel dots={{ className: "dots" }} ref={carouselRef}>
          {Array(page)
            .fill(0)
            .map((_, index) => {
              return (
                <div className="category-page" key={index}>
                  {categories
                    .slice(index * PAGE_SIZE, getSize(index + 1))
                    .map((item, indey) => {
                      return (
                        <div
                          key={item.id}
                          onClick={(e) =>
                            dispatch(changeCurrentIdAction(item.id))
                          }
                          className={classNames("category-item", {
                            active: currentId === item.id,
                          })}
                        >
                          <CategoryItemImage
                            classNames="image"
                            imgUrl={item.picWebUrl}
                          />
                          <span>{item.name}</span>
                        </div>
                      );
                    })}
                </div>
              );
            })}
        </Carousel>
      </CategoryContent>
      <div
        className="arrow arrow-right"
        onClick={(e) => carouselRef.current.next()}
      ></div>
    </CategoryWrapper>
  );
});
